package org.znxs.znagent_s.rag.myDefinition.queryTransformer;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义查询重写 翻译转换器
 */
@Component
@Slf4j
public class MyQueryTransformer {

    // 百度翻译API地址
    private static final String TRANSLATE_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    @Value("${com.baidu.appId}")
    private String APPID;

    @Value("${com.baidu.secret}")
    private String SECRET;

    /**
     * 通过第三方 翻译 api 进行提示词翻译转换
     *
     * @param prompt
     * @return
     */
    public String doQueryTransformation(String prompt, String fromLanguage, String toLanguage) {

        //随机数
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String sign = new Digester(DigestAlgorithm.MD5)
                .digestHex(APPID + prompt + salt + SECRET);
        log.info("appid:{}", APPID);
        log.info("secret:{}", SECRET);
        //封装请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("q", prompt);
        params.put("from", fromLanguage);
        params.put("to", toLanguage);
        params.put("appid", APPID);
        params.put("salt", salt);
        params.put("sign", sign);

        // 发送POST请求
        HttpResponse response = HttpRequest.post(TRANSLATE_URL)
                .form(params) // application/x-www-form-urlencoded
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject json = JSONUtil.parseObj(body);
            if (json.containsKey("trans_result")) {
                List<JSONObject> results = json.getJSONArray("trans_result").toList(JSONObject.class);
                StringBuilder sb = new StringBuilder();
                for (JSONObject result : results) {
                    sb.append(result.getStr("dst"));
                }
                return sb.toString();
            } else {
                throw new RuntimeException("Translation failed: " + body);
            }
        } else {
            throw new RuntimeException("HTTP request failed: " + response.getStatus());
        }
    }


}
